<template>
  <div v-if="editorInstance&&isEditorReady">
    <!-- 气泡菜单 - 只在选中文本且未显示弹窗时显示 -->
    <bubble-menu 
      class="bubble-menu" 
      :tippy-options="tippyOptions" 
      :should-show="shouldShowBubbleMenu" 
      :editor="editorInstance"
    >
      <el-button  @click="handleButtonClick" v-if="!showPopup">
        联网搜索
      </el-button>

      <el-button @click="addComment">
        添加批注
      </el-button>
      <el-button @click="explain">
         解释关键字
      </el-button>
      

    </bubble-menu>

    <!-- 使用封装的浮动弹窗组件 -->
    <SearchPopup v-model:visible="showPopup" :selected-text="selectedText" :editor-instance="editorInstance"
      :search-results="searchResults" @clear-results="searchResults = ''" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed ,onMounted,onBeforeUnmount} from 'vue'
import { storeToRefs } from 'pinia'
import { BubbleMenu } from '@tiptap/vue-3'
import { shouldShowBubble, tippyOptions, selectedText } from '@/components/index-center-s/bubble-menu/bubble'
import { useEditorStore } from "@/stores/editStore"
import SearchPopup from './search-popup/index.vue' // 导入封装的组件
import { addComment } from './comment/comment'
import { explainStore } from '@/stores/explain'
import { useSearchStore } from '@/stores/searchPopup'
import aiReq from '@/utils/fetchConfig';
const editorStore = useEditorStore()
const { editorInstance } = storeToRefs(editorStore)
const showPopup = ref(false)
const isEditorReady = ref(false)
const errorMessage = ref(false)
// 自定义shouldShow逻辑，当显示弹窗时不显示气泡菜单
const shouldShowBubbleMenu = ({ editor }) => {
  return shouldShowBubble({ editor }) && !showPopup.value
}


/**
 * 触发右侧解释
 */
const explain = ()=>{
   const explain =  explainStore()
   const {selection,isExplain} = storeToRefs(explain)
    selection.value = selectedText.value //watch
    isExplain.value = true
  //  isExplain = true //监听
   console.log( isExplain.value)
}
const searchStore = useSearchStore();
const searchResults = ref<string>('')
const isLoading = ref(false)
// 点击按钮处理
const handleButtonClick = async () => {
  if (!selectedText.value) return
  
  try {
    showPopup.value = true
    isLoading.value = true
    errorMessage.value = null
    searchResults.value = '' // 清空之前的结果
    
    const query = "搜索并且总结" + selectedText.value
    const response = await aiReq.streamReq(JSON.stringify({ query }))
    
    if (!response.ok) {
      throw new Error('请求失败')
    }
    
    // 处理流式响应
    const reader = response.body?.getReader()
    if (!reader) {
      throw new Error('无法读取响应流')
    }
    
    const decoder = new TextDecoder()
    while (true) {
      const { done, value } = await reader.read()
      if (done) break
      
      const chunk = decoder.decode(value, { stream: true })
      searchResults.value += chunk
    }
    
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : '请求过程中发生错误'
    console.error('请求出错:', error)
  } finally {
    isLoading.value = false
  }
}

onMounted(() => {
  setTimeout(() => {
    isEditorReady.value = !!editorInstance?.value;
  }, 100);
});

onBeforeUnmount(() => {
  isEditorReady.value = false;
});
</script>

<style lang="scss">
@use "sass:color";

.bubble-menu {
  display: flex;
  background-color: #fff;
  padding: 0.2rem;
  border-radius: 0.5rem;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05), 0 1px 2px 0 rgba(0, 0, 0, 0.1);
}


/* ================ 颜色变量 ================ */
$primary: #4361ee; // 主蓝色
$primary-light: color.adjust($primary, $lightness: 30%); // 浅蓝背景
$primary-dark: color.adjust($primary, $lightness: -10%); // 深蓝悬停
$text: #2b2d42; // 正文深灰
$text-light: #4a4e69; // 副文本
$border: #e9ecef; // 边框浅灰
$code-bg: #f8f9fa; // 代码块背景
$quote-border: #adb5bd; // 引用边框
$shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
$shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);

/* ================ 编辑器核心样式 ================ */
.tiptap {
  line-height: 1.6;
  color: $text;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
  padding: 1rem;

  /* 首元素顶部间距清零 */
  > :first-child {
    margin-top: 0;
  }

  /* 段落样式 */
  p {
    margin: 0.8rem 0;
    font-size: 1rem;
  }

  /* 标题系统 */
  h1,
  h2,
  h3,
  h4,
  h5,
  h6 {
    line-height: 1.3;
    font-weight: 600;
    color: color.adjust($text, $lightness: -10%);
    margin: 1.5rem 0 1rem;
  }

  h1 {
    font-size: 1.8rem;
    border-bottom: 1px solid $border;
    padding-bottom: 0.5rem;
  }

  h2 {
    font-size: 1.5rem;
  }

  h3 {
    font-size: 1.3rem;
  }

  h4 {
    font-size: 1.1rem;
  }

  h5 {
    font-size: 1rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: $text-light;
  }

  h6 {
    font-size: 0.9rem;
    color: $text-light;
  }

  /* 列表样式 */
  ul,
  ol {
    padding-left: 1.5rem;
    margin: 1rem 0;

    li {
      margin: 0.3rem 0;

      &::marker {
        color: $primary;
      }

      p {
        margin: 0.5rem 0;
      }
    }
  }

  ul {
    list-style-type: disc;
  }

  ol {
    list-style-type: decimal;
  }

  /* 代码样式 */
  code {
    background: $code-bg;
    color: #d63384;
    padding: 0.2em 0.4em;
    border-radius: 3px;
    font-size: 0.9em;
    font-family: 'SFMono-Regular', Menlo, Monaco, Consolas, monospace;
  }

  pre {
    background: #f8f9fa;
    border-radius: 6px;
    padding: 1rem;
    margin: 1.2rem 0;
    overflow-x: auto;
    box-shadow: $shadow-sm;
    border: 1px solid $border;

    code {
      background: transparent;
      color: inherit;
      padding: 0;
      font-size: 0.85em;
    }
  }

  /* 引用块 */
  blockquote {
    border-left: 3px solid $primary;
    margin: 1.2rem 0;
    padding: 0.8rem 1rem;
    background: $primary-light;
    border-radius: 0 4px 4px 0;
    font-style: normal;

    p {
      margin: 0;
      color: $text-light;
    }
  }

  /* 水平线 */
  hr {
    border: none;
    height: 1px;
    background: $border;
    margin: 2rem 0;
  }

  /* 图片 */
  img {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
    margin: 1rem 0;
    box-shadow: $shadow-sm;
  }

  /* 表格 */
  table {
    border-collapse: collapse;
    margin: 1rem 0;
    width: 100%;

    td,
    th {
      border: 1px solid $border;
      padding: 0.5rem 0.75rem;
    }

    th {
      background: $primary-light;
      font-weight: 600;
    }
  }
}

/* ================ 浮动工具栏 ================ */
.bubble-menu {
  background: white;
  border-radius: 8px;
  box-shadow: $shadow-md;
  display: flex;
  gap: 2px;
  padding: 4px;
  border: 1px solid $border;
  transform: translateY(-10px);
  z-index: 10;

  button {
    background: none;
    border: none;
    padding: 6px 10px;
    border-radius: 4px;
    cursor: pointer;
    color: $text-light;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      background: color.adjust($border, $lightness: 5%);
      color: $primary;
    }

    &.is-active {
      background: $primary;
      color: white;

      &:hover {
        background: $primary-dark;
      }
    }

    svg {
      width: 18px;
      height: 18px;
    }
  }
}

.floating-menu {
  @extend .bubble-menu;
  margin-bottom: 10px;
  position: absolute;
  left: 0;
  top: -44px;

  button {
    padding: 8px 12px;
  }
}

/* ================ 暗黑模式适配 ================ */
@media (prefers-color-scheme: dark) {
  .tiptap {
    color: var(--color-text);

    h1,
    h2,
    h3,
    h4,
    h5,
    h6 {
      color: var(--color-text);
    }

    code {
      background: color.adjust($text, $lightness: -20%);
    }

    pre {
      background: color.adjust($text, $lightness: -30%);
      border-color: color.adjust($text, $lightness: -15%);
    }

    blockquote {
      // background: color.adjust($primary, $lightness: -40%, $saturation: -30%);
      border-left-color: $primary-dark;
    }
  }

  .bubble-menu,
  .floating-menu {
    background: #1e293b;
    border-color: #334155;

    button {
      color: #94a3b8;

      &:hover {
        background: #334155;
      }

      &.is-active {
        background: $primary;
        color: white;
      }
    }
  }
}
</style>